const express = require('express');
const router = express.Router();
const mongoose = require('../../db/db.js');
const deviceSchema = require('../../db/cloudControl/deviceSchema');
const groupSchema = require('../../db/cloudControl/groupSchema');

router.get('/pageList', async (req,res)=>{
	try {
		const { userName, userId } = req.session;
		const {page,limit} = req.query;

		const groupMod = mongoose.model(`group_${userName}`, groupSchema);

		const count = await groupMod.countDocuments({});
		const docs = await groupMod.find({}).sort({ 'deviceName': 1 }).skip((page - 1) * limit).limit(parseInt(limit) || 20).exec();
		res.json({
			code: 0,
			msg: '',
			count: count,
			data: docs
		});
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message
		})
	}
})

router.post('/update',async(req,res)=>{
	try {
		const {userName,userId} = req.session;
		const {_id,groupName} = req.body;

		const groupMod = mongoose.model(`group_${userName}`, groupSchema);

		const result = await groupMod.updateOne({_id},{$set:{groupName}}).exec();

		res.json({
			code: 0,
			msg: '更新成功',
			data: result
		})
	}catch (error) {
		res.json({
			code: -1,
			msg: error.message
		})
	}
})

router.post('/del',async(req,res)=>{
	try {
		const {userName,userId} = req.session;
		const {_id} = req.body;
		const groupMod = mongoose.model(`group_${userName}`, groupSchema);
		const deviceMod = mongoose.model(`device_${userName}`, deviceSchema);
		await deviceMod.updateMany({groupId:_id},{$set:{groupId:null}}).exec();
		const result = await groupMod.deleteOne({_id}).exec();
		res.json({
			code: 0,
			msg: '删除成功',
			data: result
		})
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message
		})
	}
})

router.post('/add',async(req,res)=>{
	try {
		const {userName,userId} = req.session;
		const {groupName} = req.body;
		const groupMod = mongoose.model(`group_${userName}`, groupSchema);
		const result = await groupMod.create({groupName});
		res.json({
			code: 0,
			msg: '添加成功',
			data: result
		})
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message
		})
	}
})

module.exports = router;